/*
 * @Author: Dee Dee
 * @Date: 2021-05-17 00:59:20
 * @LastEditors: Dee Dee
 * @LastEditTime: 2023-09-27 16:02:15
 * @FilePath: /培训认证系统20230926/src/permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import defaultSettings from './settings'
NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register','/sso/callback', '/forgot-password', '/reset-password']

router.beforeEach((to, from, next) => {
    NProgress.start()
    if (getToken()) {
        /* has token*/

        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            // console.log("dang",store.getters.cur_role)
            if (store.getters.roles.length === 0) {
                // 判断当前用户是否已拉取完user_info信息
                store.dispatch('GetInfo',store.getters.cur_role).then(res => {
                    // 拉取user_info
                    const roles = res.user.role
                    store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
                
                        // 根据roles权限生成可访问的路由表
                        router.addRoutes(accessRoutes) // 动态添加可访问路由表
                        next({...to, replace: true }) // hack方法 确保addRoutes已完成
                    })
                }).catch(err => {
                    store.dispatch('LogOut').then(() => {
                        // Message.error(err)
                        next({ path: '/' })
                    })
                })
            } else {
                next()
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            if (!defaultSettings.casEnable) {
                // 否则全部重定向到登录页
                next(`/login?redirect=${to.fullPath}`)
            }
            //开启cas
            if (defaultSettings.casEnable) {
                // 否则全部重定向到登录页
                window.location.href = defaultSettings.casloginUrl
            }


            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})